package org.jeecg.modules.tencent.handle;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.modules.doctor.entity.DoctorWxUserinfoRelation;
import org.jeecg.common.modules.doctor.service.IDoctorWxUserinfoRelationService;
import org.jeecg.common.modules.wx.entity.WxUserinfo;
import org.jeecg.common.modules.wx.service.IWxUserinfoService;
import org.jeecg.common.util.IMJsonUtil;
import org.jeecg.common.util.tencent.response.IMBaseResponse;
import org.jeecg.modules.abs.TencentCallBackAbstract;
import org.jeecg.modules.tencent.enums.IMCallbackEnum;
import org.jeecg.modules.tencent.vo.GroupMsgPreVo;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Objects;

import static org.jeecg.common.util.constants.IMConstants.BUY_COUNT;
import static org.jeecg.modules.tencent.util.TencentCallBackConstants.GROUP_MSG_PRE;

/**
 * @author guoyh
 * @ClassName GroupMsgPreHandle
 * @Description
 * @since 2020/8/28 23:55
 **/
@Component(value = GROUP_MSG_PRE)
@Slf4j
public class GroupMsgPreHandle extends TencentCallBackAbstract {

    @Resource
    private IDoctorWxUserinfoRelationService doctorWxUserinfoRelationService;

    @Resource
    private IWxUserinfoService wxUserinfoService;



    @Override
    public IMCallbackEnum getHandleClass() {
        return IMCallbackEnum.GROUP_MSG_PRE;
    }

    @Override
    protected IMBaseResponse handle(String body) {
//        if(1==1){
//            return IMBaseResponse.buildSuccess();
//        }
        GroupMsgPreVo groupMsgPreVo = IMJsonUtil.parse(body,GroupMsgPreVo.class);
        if (Objects.isNull(groupMsgPreVo)){
            log.error("转换消息Bean失败{}",body);
            return IMBaseResponse.buildFail("转换消息Bean失败");
        }
        DoctorWxUserinfoRelation relation = doctorWxUserinfoRelationService.getByGroupId(groupMsgPreVo.getGroupId());
        if (Objects.isNull(relation)){
            return IMBaseResponse.buildFail("未获取到医患关系");
        }
        WxUserinfo wxUserinfo = wxUserinfoService.getByOpenid(relation.getOpenid());
        //患者发送，需检查剩余图文消息条数
        if (StringUtils.equals(groupMsgPreVo.getFromAccount(),wxUserinfo.getId())){
            if (Objects.equals(BUY_COUNT,relation.getTextNumber())){
                return IMBaseResponse.buildSuccess();
            }
            if (relation.getTextNumber() <= 0){
                return IMBaseResponse.buildFail("已无可用消息");
            }
            doctorWxUserinfoRelationService.updateTextNumber(relation.getId(),-1);
        }
        return IMBaseResponse.buildSuccess();
    }
}
